package com.codingapi.websocket.core.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.codingapi.websocket.core.client.WebSocketSession;
import com.codingapi.websocket.core.util.JsonUtils;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author modificial
 * @date 2018/7/19
 * @company codingApi
 * @description 默认实现，可以在此类执行业务逻辑
 */
@Component
public class SimpleWebSocketHandler implements WebSocketHandler {

    private static final Logger LOGGER = LoggerFactory.getLogger(SimpleWebSocketHandler.class);
    /**
     * 心跳检测信息
     */
    private static final String HEARTBEAT_MESSAGE="heartbeat";
    /**
     * 用户信息
     */
    private static final String USER_MESSAGE="userId";
    /**
     * 心跳Ok
     */
    private static final String HEART_BEAT_OK="OK";
    /**
     * 维护socket连接参数
     */
    private static Map<String, WebSocketSession> socketMap = new ConcurrentHashMap<>();

    @Override
    public void beforeConnectionUpgraded(WebSocketSession webSocketSession) {
        LOGGER.info("开始连接-----");
    }

    @Override
    public void afterConnectionEstablished(WebSocketSession webSocketSession) {
        TextWebSocketFrame textWebSocketFrame = new TextWebSocketFrame("连接成功");
        webSocketSession.sendMessage(textWebSocketFrame);
        LOGGER.info("连接成功-----");
    }

    @Override
    public synchronized void handleMessage(WebSocketSession webSocketSession, WebSocketFrame webSocketFrame) {
        if (webSocketFrame instanceof TextWebSocketFrame) {
            TextWebSocketFrame textWebSocketFrame = (TextWebSocketFrame) webSocketFrame;
            String msg = textWebSocketFrame.text();
            if (StringUtils.hasText(msg)&& JsonUtils.isJSONValid(msg)) {
                JSONObject jsonObject = JSON.parseObject(msg);
                if (jsonObject.containsKey(USER_MESSAGE)&& Objects.deepEquals(HEART_BEAT_OK,jsonObject.getString(HEARTBEAT_MESSAGE).toUpperCase())) {
                    String userId = jsonObject.getString(USER_MESSAGE);
                   LOGGER.info("放入map--"+webSocketSession.getId());
                   socketMap.putIfAbsent(userId,webSocketSession);
                   WebSocketFrame feedBack=new TextWebSocketFrame("连接正常");
                   webSocketSession.sendMessage(feedBack);
                   LOGGER.info("向目标客户端反馈-----"+feedBack);
                }
            }
           LOGGER.info("接收到参数---"+msg);
        }
    }

    @Override
    public void handleTransportError(WebSocketSession webSocketSession, Throwable throwable) {
        LOGGER.error("连接出错");
        WebSocketFrame feedBack=new TextWebSocketFrame("连接出错");
        webSocketSession.sendMessage(feedBack);
        if(socketMap.containsValue(webSocketSession)){
         socketMap.remove(webSocketSession);
        }
        webSocketSession.close();
    }

    @Override
    public void afterConnectionClosed(WebSocketSession webSocketSession) {
        TextWebSocketFrame textWebSocketFrame = new TextWebSocketFrame("连接关闭");
        webSocketSession.sendMessage(textWebSocketFrame);
        if(socketMap.containsValue(webSocketSession)){
            LOGGER.info("开始移除连接"+webSocketSession.getId());
            socketMap.remove(webSocketSession);
        }
        webSocketSession.close();
        LOGGER.info("连接关闭");
    }

    @Override
    public boolean supportsPartialMessages() {

        return false;
    }

    public static Map<String, WebSocketSession> getSocketMap() {
        return socketMap;
    }
}
